package com.ioidea.room.bean

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow

//group_id 从1开始  1..9  1是默认分组不能修改
const val DEFAULT_GROUP_ID = 1


/**
 * @param lightSn   灯的sn
 * @param groupName 组名称 从另外一张表来的

 */
data class JkChildDevExt(
    override var lightSn: String,
    var groupName: String? = "",

) : JkChildDev(lightSn) {

}
/**
 * 集控器下的子设备
 * @param lightSn
 * @param light 亮度
 * @param groupId 组
 * @param controlType 控制类型  单控  群控  组控
 * @param showType    显示标题还是内容
 * @param isOldDev  同步白名单和数据库的数据  处理灯被拔掉的情况
 */
@Entity
open class JkChildDev(
    @PrimaryKey
    open var lightSn: String,
    open var light1: Int = 0,
    open var groupId: Int = DEFAULT_GROUP_ID,
    open var controlType: Int = 0,//默认群控
    open var jkSn: String = "",
    open var light2:Int=0,
    open var light3:Int=0,
    ) {
//    @Ignore
//    @Transient
//    var groupName: String = ""

    @Ignore
    @Transient
    var showType: Int = 2//默认显示内容
    @Ignore
    @Transient
    var isOldDev: Boolean = true
}

@Dao
interface JKChildDevDao {


    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertJkChildDev(device: JkChildDev)

    @Update
    fun replaceJkChildDev(device: JkChildDev)

    @Query("DELETE FROM JkChildDev WHERE jkSn=:jkSn")
    fun clearJkChildDevByJKSn(jkSn: String)


    @Query("SELECT * FROM JkChildDev")
    fun getAllJkChildDevsFlow(): Flow<MutableList<JkChildDev>>

    @Query("SELECT * FROM JkChildDev")
    fun getAllJkChildDevsList(): List<JkChildDev>

    @Query(
        "SELECT d.*, g.groupName FROM JkChildDev d LEFT JOIN GroupName g ON d.groupId = g.groupId AND g.jkSn=:jkSn WHERE d.jkSn=:jkSn ORDER BY d.lightSn DESC "
    )
    fun getJkChildDevsByJkSnList(jkSn: String): MutableList<JkChildDevExt>

    @Query(
        "SELECT d.*, g.groupName FROM JkChildDev d LEFT JOIN GroupName g ON d.groupId = g.groupId AND g.jkSn=:jkSn WHERE d.jkSn=:jkSn ORDER BY d.lightSn DESC "
    )
    fun getJkChildDevsByJkSnFlow(jkSn: String): Flow<MutableList<JkChildDevExt>>


    //A集控器下的灯  拔到B集控器下去
    @Query(
        "SELECT * FROM JkChildDev WHERE lightSn=:lightSn AND jkSn=:jkSn"
    )
    fun getJkChildDevBySn(lightSn: String,jkSn: String): JkChildDev?

    @Query(
        "SELECT * FROM JkChildDev WHERE lightSn=:sn"
    )
    fun getJkChildDevBySnFlow(sn: String): Flow<JkChildDev?>


    //可能组下设备为0
    @Delete
    fun deleteJkChildDev(device: JkChildDev)

    @Query("DELETE FROM JkChildDev WHERE lightSn = :lightSn AND jkSn = :jkSn;")
    fun deleteJkChildDev(lightSn: String,jkSn: String)

}



